package com.book.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.io.PrintWriter;


@WebServlet("/enroll")
public class enroll extends HttpServlet {

    private static final long serialVersionUID = 1L;
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String URL = "jdbc:mysql://127.0.0.1:3306/library?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true";
    static final String USER = "root";
    static final String PASS = "1234";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String pass = req.getParameter("pass");
        String passuser = req.getParameter("passagain");
        if (passuser.equals(pass)) {
        } else {
            req.getRequestDispatcher("/worry2.html").forward(req, resp);
        }
        Connection conn = null;
        Statement stmt = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(URL, USER, PASS);
            stmt = conn.createStatement();
            String sql = "select * from user";
            int iduser = 1;
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                iduser = iduser + 1;
            }
            String addsql = "INSERT INTO user(id,passnum) VALUES(?,?)";
            ps = conn.prepareStatement(addsql);
            ps.setInt(1, iduser);
            ps.setString(2, pass);
            ps.executeUpdate();

            resp.setContentType("text/html;charset=utf-8");
            PrintWriter out = resp.getWriter();
            out.println("<html>");
            out.println("<head>");
            out.println("<script>");
            out.println("var generatedId = " + iduser + ";");
            out.println("alert('您的新 ID 值是：' + generatedId+' , 点击确认后跳转至登录界面');");
            out.println("window.location.href='a.html'");
            out.println("</script>");
            out.println("</head>");
            out.println("<body>");
            out.println("</body>");
            out.println("</html>");
            rs.close();
            stmt.close();
            conn.close();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

